package com.fs.global.config;

import com.fs.service.WxPayService;
import com.wechat.pay.contrib.apache.httpclient.auth.AutoUpdateCertificatesVerifier;
import com.wechat.pay.contrib.apache.httpclient.auth.PrivateKeySigner;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Credentials;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.util.Assert;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.PrivateKey;

@Configuration
public class WechatConfig implements EnvironmentAware {
    private Environment environment;

    @Bean
    public WxPayConfig wxPayConfig() throws FileNotFoundException {
        WxPayConfig payConfig = new WxPayConfig();
        Assert.notNull(environment.getProperty("custom.wechat.mchId"), "没有商户Id");
        payConfig.setMchId(environment.getProperty("custom.wechat.mchId"));

        Assert.notNull(environment.getProperty("custom.wechat.appId"), "没有appId");
        payConfig.setAppId(environment.getProperty("custom.wechat.appId"));

        Assert.notNull(environment.getProperty("custom.wechat.appSecret"), "没有appSecret");
        payConfig.setAppSecret(environment.getProperty("custom.wechat.appSecret"));

        Assert.notNull(environment.getProperty("custom.wechat.mchSerialNo"), "没有商户证书号");
        payConfig.setMchSerialNo(environment.getProperty("custom.wechat.mchSerialNo"));

        Assert.notNull(environment.getProperty("custom.wechat.v3Key"), "没有v3Key");
        payConfig.setV3Key(environment.getProperty("custom.wechat.v3Key"));

        Assert.notNull(environment.getProperty("custom.wechat.notifyUrl"), "没有notifyUrl");
        payConfig.setNotifyUrl(environment.getProperty("custom.wechat.notifyUrl"));

        Assert.notNull(environment.getProperty("custom.wechat.mchKeyPath"), "没有mchKeyPath");
        payConfig.setMchKeyPath(environment.getProperty("custom.wechat.mchKeyPath"));

        InputStream is = new FileInputStream(payConfig.getMchKeyPath());
        payConfig.setPrivateKey(PemUtil.loadPrivateKey(is));

        AutoUpdateCertificatesVerifier verifier = new AutoUpdateCertificatesVerifier(
                new WechatPay2Credentials(payConfig.getMchId(),
                        new PrivateKeySigner(payConfig.getMchSerialNo(), payConfig.getPrivateKey())),
                payConfig.getV3Key().getBytes(StandardCharsets.UTF_8));
        payConfig.setVerifier(verifier);

        return payConfig;
    }

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }


}
